###########################
# 1. Conduct preferred analysis
###########################

library(stargazer)
library(tidyr)
library(lme4)
library(MuMIn)
library(broom)
library(dplyr)
library(ggplot2)
load('analysis.RData')


###
# 1. Preferred model analysis

# a. Final model prep
analysis$party_place <- ifelse(analysis$party == 'Democrat', analysis$dem_place, analysis$gop_place) # the DV - ha!
analysis$same_party <- ifelse(analysis$party == analysis$R_party, 1, 0)
analysis$year1 <- analysis$year - 1990

# b. Preferred model -- change that can occur
model_can <- lmer(party_place ~ std_nominate + std_state_npat + std_ntl_symbolic + 
              party + party*st_knowledge + self_place*same_party + same_party*party +
                (1 | party:state:year) + nonwhite + bach + male + over50, data = analysis, weights = adjusted_weight)
summary(model_can)
can_preds <- predict(model_can, model_can@frame)
cor(can_preds, model_can@frame$party_place)^2

model_does <- lmer(party_place ~ std_party_nominate + std_party_state_npat + std_party_ntl_symbolic + 
                  party + party*st_knowledge + self_place*same_party + same_party*party +
                   (1 | party:state:year)  + nonwhite + bach + male + over50, data = analysis, weights = adjusted_weight)
summary(model_does)
does_preds <- predict(model_does, model_does@frame)
cor(does_preds, model_does@frame$party_place)^2

# c. Do the output
stargazer(model_can, model_does, 
          type = "html",
          out = "model_summaries.html",
          star.cutoffs = c(0.05, 0.01, 0.001),
          custom.note = "Note: * p<.05, ** p<.01, *** p<.001")
